package com.gitee.wsl.serialization.base


import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

typealias BytesValueP = @Serializable(with = BytesValueSerializer::class) ByteArray?

object BytesValueSerializer : KSerializer<ByteArray?> {
    @Serializable
    private data class Boxed(
        val `value`: ByteArray = ByteArray(0)
    ) {
        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (other !is Boxed) return false

            if (!`value`.contentEquals(other.`value`)) return false

            return true
        }

        override fun hashCode(): Int {
            return `value`.contentHashCode()
        }
    }

    override val descriptor: SerialDescriptor = Boxed.serializer().descriptor
    @OptIn(ExperimentalSerializationApi::class)
    override fun serialize(encoder: Encoder, value: ByteArray?) {
        encoder.encodeNullableSerializableValue(Boxed.serializer(), value?.let { Boxed(it) })
    }

    @OptIn(ExperimentalSerializationApi::class)
    override fun deserialize(decoder: Decoder): ByteArray? {
        return decoder.decodeNullableSerializableValue(Boxed.serializer())?.`value`
    }
}